import React, { createContext, useContext, useState, useEffect, type ReactNode } from 'react';

interface AuthContextType {
  isAuthenticated: boolean;
  userPhone: string | null;
  login: (phone: string) => void;
  logout: () => void;
  showLoginModal: boolean;
  setShowLoginModal: (show: boolean) => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [userPhone, setUserPhone] = useState<string | null>(null);
  const [showLoginModal, setShowLoginModal] = useState(false);

  // 从localStorage恢复登录状态
  useEffect(() => {
    const savedPhone = localStorage.getItem('userPhone');
    const savedAuth = localStorage.getItem('isAuthenticated');
    
    if (savedPhone && savedAuth === 'true') {
      setUserPhone(savedPhone);
      setIsAuthenticated(true);
    }
  }, []);

  const login = (phone: string) => {
    setUserPhone(phone);
    setIsAuthenticated(true);
    setShowLoginModal(false);
    
    // 保存到localStorage
    localStorage.setItem('userPhone', phone);
    localStorage.setItem('isAuthenticated', 'true');
  };

  const logout = () => {
    setUserPhone(null);
    setIsAuthenticated(false);
    
    // 清除localStorage
    localStorage.removeItem('userPhone');
    localStorage.removeItem('isAuthenticated');
  };

  const value: AuthContextType = {
    isAuthenticated,
    userPhone,
    login,
    logout,
    showLoginModal,
    setShowLoginModal
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};
